package com.guimin.common.util;

/**
 * 雪花ID生成器
 * @author Hezy
 * @since 2021/01/16 17:51
 */
public class SnowflakeIdWorker {
    /**
     * 起始的时间戳
     */
    private static final long START_TIMESTAMP = 1609430400000L;
    /** 数据中心占用的位数 */
    private static final long DATACENTER_BIT = 5L;
    /** 工作机器标识占用的位数 */
    private static final long MACHINE_BIT = 5L;
    /** 序列号占用的位数 */
    private static final long SEQUENCE_BIT = 12L;
    /**
     * 每一部分的最大值
     */
    private static final long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    private static final long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
    /**
     * 每一部分向左的位移
     */
    private static final long MACHINE_LEFT_SHIFT = SEQUENCE_BIT;
    private static final long DATACENTER_LEFT_SHIFT = SEQUENCE_BIT + MACHINE_BIT;
    private static final long TIMESTAMP_LEFT_SHIFT = DATACENTER_LEFT_SHIFT + DATACENTER_BIT;
    /** 数据中心标识 */
    private long datacenterId;
    /** 工作机器标识 */
    private long machineId;
    /** 毫秒内序列(0~4095) */
    private long sequence = 0L;
    /** 上次生成ID的时间截 */
    private long lastTimestamp = -1L;
    /**
     * 构造函数
     * @param datacenterId 数据中心ID (0~31)
     * @param machineId 工作机器ID (0~31)
     */
    public SnowflakeIdWorker(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }
    /**
     * 产生下一个ID
     * @return 雪花id
     */
    public synchronized long nextId() {
        long currentTimestamp  = System.currentTimeMillis();
        if (currentTimestamp  < lastTimestamp) {
            //时钟回退，报错
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }
        if (currentTimestamp  == lastTimestamp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currentTimestamp  = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }
        lastTimestamp = currentTimestamp ;
        return (currentTimestamp  - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT  //时间戳部分
                | datacenterId << DATACENTER_LEFT_SHIFT  //数据中心部分
                | machineId << MACHINE_LEFT_SHIFT  //机器标识部分
                | sequence;  //序列号部分
    }
    private long getNextMill() {
        long mill;
        do{
            mill = System.currentTimeMillis();
        }while (mill <= lastTimestamp);
        return mill;
    }

    /**
     * 创建雪花id
     * 允许传入自定义初始时间戳
     * @param startTimestamp 初始时间戳
     * @return 雪花id
     */
    public synchronized long nextId(long startTimestamp){
        long currentTimestamp  = System.currentTimeMillis();
        if (currentTimestamp  < lastTimestamp || currentTimestamp < startTimestamp) {
            //时钟回退，报错
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }
        if (currentTimestamp  == lastTimestamp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currentTimestamp  = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }
        lastTimestamp = currentTimestamp ;
        return (currentTimestamp  - startTimestamp) << TIMESTAMP_LEFT_SHIFT  //时间戳部分
                | datacenterId << DATACENTER_LEFT_SHIFT  //数据中心部分
                | machineId << MACHINE_LEFT_SHIFT  //机器标识部分
                | sequence;  //序列号部分
    }
}